<template>
  <div class="mod-config">
    <el-form :inline="true" :model="dataForm" @keyup.enter.native="getDataList()">
      <el-form-item label="员工姓名">
        <el-input v-model="dataForm.username" clearable placeholder="姓名"></el-input>
      </el-form-item>
      <el-form-item label="性别" prop="type">
        <el-select v-model="dataForm.sex" clearable placeholder="请选择" style="width: 100%">
          <el-option label="男" value="1"></el-option>
          <el-option label="女" value="2"></el-option>
          <el-option label="未知" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="角色" prop="role">
        <el-select v-model="dataForm.role" clearable placeholder="请选择" style="width: 100%">
          <el-option label="管理员" value="1"></el-option>
          <el-option label="发餐人" value="2"></el-option>
          <el-option label="员工" value="3"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="生日日期">
        <el-date-picker v-model="dataForm.range" type="daterange" range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd" format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button @click="getDataList()">查询</el-button>
        <el-button type="primary" @click="addOrUpdateHandle()">新增</el-button>
        <el-button type="danger" @click="deleteHandle()" :disabled="dataListSelections.length <= 0">批量删除</el-button>
        <el-button type="success" @click="uploadExcel()">批量导入</el-button>
      </el-form-item>
    </el-form>
    <el-table :data="dataList" border
      v-loading="dataListLoading"
      @selection-change="selectionChangeHandle"
      style="width: 100%;"
      :header-cell-style="{background:'#f2f2f2',color:'#666'}">
      <el-table-column
        type="selection"
        header-align="center"
        align="center"
        width="50">
      </el-table-column>
      <el-table-column prop="id" header-align="center" align="center" width="80" label="ID"></el-table-column>
      <el-table-column prop="username" header-align="center" align="center" label="员工姓名"></el-table-column>
      <el-table-column prop="idNumber" header-align="center" align="center" label="身份证号后6位"></el-table-column>
      <el-table-column prop="number" header-align="center" align="center" label="工号"></el-table-column>
      <el-table-column prop="telnum" header-align="center" align="center" label="手机号"></el-table-column>
      <el-table-column prop="birthday" header-align="center" align="center" label="职工生日"></el-table-column>
      <el-table-column prop="age" header-align="center" align="center" label="年龄"></el-table-column>
      <el-table-column prop="sex" header-align="center" align="center" label="性别" width="100px">
        <template slot-scope="scope">
          <div v-if="scope.row.sex === 1">男</div>
          <div v-if="scope.row.sex === 2">女</div>
          <div v-if="scope.row.sex === 3">未知</div>
        </template>
      </el-table-column>
        <el-table-column prop="roleId" header-align="center" align="center" label="角色" width="100px">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.roleId === 1" size="small" type="success">管理员</el-tag>
          <el-tag v-if="scope.row.roleId === 2" size="small" type="warning">发餐人</el-tag>
          <el-tag v-if="scope.row.roleId === 3" size="small" type="info">员工</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" label="添加时间"></el-table-column>
      <el-table-column fixed="right" header-align="center" align="center" label="操作">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="addOrUpdateHandle(scope.row.id,scope.row.pid)">编辑</el-button>
          <el-button size="small" type="text" @click="lookDetailsInfo(scope.row)">详情</el-button>
          <el-button size="small" type="text" @click="deleteHandle(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    ></el-pagination>

    <el-dialog
      title="批量导入"
      :visible.sync="uploadVisible"
      width="30%"
      :before-close="handleClose">
      <div>
        <a href="https://lgdapi.weeli.cn/resources/file.xlsx" >1、点击下载导入数据模板 </a>
        <span> 将要导入的数据填充到数据导入模板文件中。</span>
      </div>
        <div>注意事项：</div>
        <div>1）模板中的表头不可更改，表头行不可删除</div>
        <div>2）除必填的列以外，不需要的列可以删除；</div>
        <div>3）单次导入的数据不超过10000条。</div>
        <div>2、选择要导入的数据文件</div>
      <span slot="footer" class="dialog-footer">
          <div>
            <el-upload
              class="avatar-uploader"
              :action="actionUpload"
              :show-file-list="false"
              :on-change="handleChange"
              :on-success="handleAvatarSuccess"
              :before-upload="beforeAvatarUpload"
              accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel">
              <el-button size="small" type="primary">开始导入</el-button>
          </el-upload>
        </div>
      </span>
    </el-dialog>

    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @refreshDataList="getDataList"></add-or-update>

     <!-- 详情对话框 -->
    <el-dialog :visible.sync="detailsModel" title="详情">
      <el-form :data="detailInfo">
        <el-form-item label="员工姓名:">
          <span>{{ detailInfo.username}}</span>
        </el-form-item>
        <el-form-item label="身份证号后6位:">
          <span>{{ detailInfo.idNumber }}</span>
        </el-form-item>
        <el-form-item label="工号:">
          <span>{{ detailInfo.number }}</span>
        </el-form-item>
        <el-form-item label="手机号:">
          <span>{{ detailInfo.telnum }}</span>
        </el-form-item>
        <el-form-item label="职工生日	:">
          <span>{{ detailInfo.birthday }}</span>
        </el-form-item>
        <el-form-item label="年龄	:">
          <span>{{ detailInfo.age }}</span>
        </el-form-item>
        <el-form-item label="性别	:">
          <div>
            <div v-if="detailInfo.sex === 1" type="warning">男</div>
            <div v-if="detailInfo.sex === 2" type="success">女</div>
            <div v-if="detailInfo.sex === 3" type="info">未知</div>
          </div>
        </el-form-item>
        <el-form-item label="添加时间	:">
          <span>{{ detailInfo.createTime }}</span>
        </el-form-item>
         <el-form-item label="角色 :">
           <el-button v-if="detailInfo.roleId==1" size="small" type="text">管理员</el-button>
           <el-button v-if="detailInfo.roleId==2" size="small" type="text">发餐人</el-button>
           <el-button v-if="detailInfo.roleId==3" size="small" type="text">员工</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import AddOrUpdate from './staff-add-or-update'
export default {
  data() {
    return {
      actionUpload: "http://121.4.86.70:9090",
      dataForm: {
        username: '',
        sex: '',
        role: '',
        range: ''
      },
      dataListSelections: [],
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      addOrUpdateVisible: false,
      detailsModel:false,
      uploadVisible:false,
      detailInfo:{},
      fileTemp:null,
      fileListUpload:[]
    }
  },
  components: {
    AddOrUpdate
  },
  activated() {
    this.getDataList()
  },
  mounted() {
    this.actionUpload = this.$http.adornUrl(
      `/common/file/uploadExcel?token=${this.$cookie.get("token")}`
    );
  },
  methods: {
     // 获取数据列表
      getDataList () {
          this.dataListLoading = true
          let startTime = null
          let endTime = null
          if (this.dataForm.range && this.dataForm.range.length > 1) {
            startTime = this.dataForm.range[0];
            endTime = this.dataForm.range[1];
          }
          this.$http({
          url: this.$http.adornUrl('/staff/list'),
          method: 'get',
          params: this.$http.adornParams({
            username: this.dataForm.username,
            page: this.pageIndex,
            limit: this.pageSize,
            sex:this.dataForm.sex,
            role:this.dataForm.role,
            startTime: startTime,
            endTime: endTime,
          })
          }).then(({data}) => {
          if (data && data.code === 0) {
              this.dataList = data.page.list
              this.totalPage = data.page.totalCount
          } else {
              this.dataList = []
              this.totalPage = 0
          }
          this.dataListLoading = false
          })
      },
    // 每页数
    sizeChangeHandle(val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle(val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 新增 / 修改
    addOrUpdateHandle(id) {
      this.addOrUpdateVisible = true
      this.$nextTick(() => {
        this.$refs.addOrUpdate.init(id)
      })
    },
    // 查看详情模态框
    lookDetailsInfo(row) {
      this.detailsModel = true
      this.detailInfo = row
    },
    getDetailsInfo(id) {
      this.$http({
        url: this.$http.adornUrl(`/market/info/${id}`),
        method: "get",
        params: this.$http.adornParams(),
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.detailInfo = data.info;
        } else {
          this.$message.error(data.msg);
        }
        this.loading = false;
      });
    },
    uploadExcel(){
      this.uploadVisible = true
    },
    handleChange(file, fileList){
      this.uploadVisible = false;
      this.fileTemp = file.raw
      if(this.fileTemp){
        if((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') || (this.fileTemp.type == 'application/vnd.ms-excel')){
            // this.importfxx(this.fileTemp)
        } else {
          this.$message({
              type:'warning',
              message:'附件格式错误，请删除后重新上传！'
          })
        }
      } else {
        this.$message({
            type:'warning',
            message:'请上传附件！'
        })
      }
    },

    handleRemove(file,fileList){
      this.fileTemp = null
    },
    handleClose(){
      this.uploadVisible = false
    },
    handleExceed(files, fileList) {
      this.$message.warning(`当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
    },
    beforeAvatarUpload(file) {
      console.log("beforeAvatarUpload")
    },
    handleAvatarSuccess(res, file) {
      this.$message({
        message: '导入成功',
        type: 'success',
        duration: 1500,
        onClose: () => {
          this.getDataList()
        }
      })
    },
    handleError(err, file, fileList) {
      // 上传失败异常处理
      // const error = JSON.parse(JSON.stringify(err));
      // console.log(err);
      // console.log(error);
      // this.$message.error(error.status.toString());
      // this.videoFlag = false;
      // this.percent = 0;
      console.log("handleError")
    },
    uploadProcess(event, file, fileList) {

      console.log("uploadProcess")
      // this.videoFlag = true;
      // console.log(event.percent);
      // this.percent = Math.floor(event.percent);
    },
    // 删除
    deleteHandle(id) {
      var ids = id ? [id] : this.dataListSelections.map(item => {
        return item.id
      })
      this.$confirm(`确定对[id=${ids.join(',')}]进行[${id ? '删除' : '批量删除'}]操作?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.$http({
            url: this.$http.adornUrl('/staff/delete'),
            method: 'post',
            data: this.$http.adornData(ids, false)
          }).then(({ data }) => {
            if (data && (data.code === 0 || data.code === '0')) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.getDataList()
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        })
        .catch(() => {})
    }
  }
}
</script>

<style scoped>
</style>
